package com.suxin.netty.server;

import com.suxin.netty.protocol.ProtocolMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author Tang
 * @classname MySimpleChannelInboundHandler
 * @description [  ]
 * @date 2021/7/17 10:48
 */
public class MySimpleChannelInboundHandler extends SimpleChannelInboundHandler<ProtocolMsg> {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("注册一个socket: " + ctx.channel().hashCode());
        new Thread(() -> {
            try {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String nextLine = scanner.nextLine();
                    System.out.println("向客户端写入数据为: " + nextLine);
                    ProtocolMsg protocolMsg = new ProtocolMsg();
                    byte[] bytes = nextLine.getBytes();
                    protocolMsg.setData(bytes);
                    protocolMsg.setLen(bytes.length);
                    ctx.writeAndFlush(protocolMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "writer thread-").start();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMsg protocolMsg) throws Exception {
        System.out.println("收到客户端发来的内容为: " + new String(protocolMsg.getData(),Charset.defaultCharset()));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端数据读取完成..." + ctx.hashCode());
    }
}